<?php

declare(strict_types=1);

namespace app\admin\logic;

use app\common\logic\Config as LogicConfig;
use app\common\model\Config as ModelConfig;
use liang\MicroEngine;

/**
 * 后台管理系统 系统配置逻辑层
 */
class Config extends LogicConfig
{
    /**
     * 获取配置
     */
    public static function getConfig()
    {
        $data = ModelConfig::field('key,value')->select();
        $data = $data->column('value', 'key');
        $data['msg_url'] = self::getMessageUrl();
        return $data;
    }

    /**
     * 获取消息推送URl地址
     */
    private static function getMessageUrl()
    {
        $route = '/message/response';
        if (MicroEngine::isMicroEngine()) {
            $uri = '/app/index.php?i=' . MicroEngine::getUniacid() . '&c=entry&do=index&m=' . MicroEngine::getModuleName()  . '&s=' . $route;
        } else {
            $uri = $route;
        }
        return request()->domain() . $uri;
    }

    // +----------------------------------------------------------------------
    // | 更新配置
    // +----------------------------------------------------------------------

    /**
     * 更新系统配置通用方法
     *
     * @param array $data
     */
    public static function update(array $data)
    {
        foreach ($data as $key => $value) {
            $config = ModelConfig::where('key', $key)->findOrEmpty();
            $config->isEmpty() || $config->save(['value' => $value]);
        }
    }
}
